﻿using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;
using Klear.Library.Services;
using Ursa.Controls;

namespace Klear.Library.ViewModels;

public class MainViewModel : ViewModelBase
{
    private readonly IMenuNavigationService _menuNavigationService;
    private readonly IRemindStorage _remindStorage;
    private bool _hasBudgetWarning;
    private decimal _currentSpending;
    private decimal _warningThreshold;
    private decimal _totalBudget;
    
    public MainViewModel(IMenuNavigationService menuNavigationService,
        IRemindStorage remindStorage)
    {
        _menuNavigationService = menuNavigationService;
        _remindStorage = remindStorage;
        
        OpenPaneCommand = new RelayCommand(OpenPane);
        ClosePaneCommand = new RelayCommand(ClosePane);
        GoBackCommand = new RelayCommand(GoBack);
        OnMenuTappedCommand = new RelayCommand(OnMenuTapped);
        ShowBudgetWarningCommand = new RelayCommand(ShowBudgetWarning);
        
        // 订阅预算警告事件
        _remindStorage.BudgetWarningTriggered += OnBudgetWarningTriggered;
        
        _ = InitializeAsync();
    }
    
    private async Task InitializeAsync()
    {
        try
        {
            var currentBudget = await _remindStorage.GetCurrentBudget();
            if (currentBudget != null)
            {
                await _remindStorage.CheckBudgetWarning();
            }
        }
        catch (Exception ex)
        {
            // 处理错误
            Debug.WriteLine($"Failed to initialize budget warning: {ex}");
        }
    }
    
    // 这个title用于显示顶部的标题
    private string _title = String.Empty;

    public string Title {
        get => _title;
        private set => SetProperty(ref _title, value);
    }

    private bool _isPaneOpen;

    public bool IsPaneOpen {
        get => _isPaneOpen;
        private set => SetProperty(ref _isPaneOpen, value);
    }
    
    public bool HasBudgetWarning
    {
        get => _hasBudgetWarning;
        private set 
        {
            if (_hasBudgetWarning != value)
            {
                _hasBudgetWarning = value;
                OnPropertyChanged(nameof(HasBudgetWarning));
            }
        }
        
    }

    public ICommand ShowBudgetWarningCommand { get; }
    
    private async void ShowBudgetWarning()
    {
        if (HasBudgetWarning)
        {
            await MessageBox.ShowAsync(
                $"警告: 当前支出 (￥{_currentSpending:N2}) 已超过预警阈值 (￥{_warningThreshold:N2})！\n" +
                $"总预算: ￥{_totalBudget:N2}");
        }
    }
    
    private void OnBudgetWarningTriggered(object sender, BudgetWarningEventArgs e)
    {
        HasBudgetWarning = e.ActualSpending > e.WarningThreshold;
        _currentSpending = e.ActualSpending;
        _warningThreshold = e.WarningThreshold;
        _totalBudget = e.TotalBudget;
    }

    public override void Cleanup()
    {
        _remindStorage.BudgetWarningTriggered -= OnBudgetWarningTriggered;
        base.Cleanup();
    }

    public ICommand OpenPaneCommand { get; }

    public void OpenPane() => IsPaneOpen = true;

    public ICommand ClosePaneCommand { get; }

    public void ClosePane() => IsPaneOpen = false;

    public ObservableCollection<ViewModelBase> ContentStack { get; } = [];

    private ViewModelBase _content;

    public ViewModelBase Content {
        get => _content;
        private set => SetProperty(ref _content, value);
    }
    
    // 不涉及内容导航，这部分的内容栈（记录ViewModel）可以省略
    public void PushContent(ViewModelBase content) =>
        ContentStack.Insert(0, Content = content);

    // public void PushContent(ViewModelBase content) =>
    //     Content = content;
    
    public void SetMenuAndContent(string view, ViewModelBase content) {
        ContentStack.Clear();
        PushContent(content);
        // 在集合中查找第一个满足指定条件的元素并赋值给SelectedMenuIte,
        SelectedMenuItem =
            MenuItem.MenuItems.FirstOrDefault(p => p.View == view); 
        Title = SelectedMenuItem.Name;
        IsPaneOpen = false;
    }

    private MenuItem _selectedMenuItem;

    public MenuItem SelectedMenuItem {
        get => _selectedMenuItem;
        set => SetProperty(ref _selectedMenuItem, value);
    }

    public ICommand GoBackCommand { get; }

    public void GoBack() {
        if (ContentStack.Count <= 1) {
            return;
        }
    
        ContentStack.RemoveAt(0);
        Content = ContentStack[0];
    }

    public ICommand OnMenuTappedCommand { get; }

    public void OnMenuTapped() {
        if (SelectedMenuItem is null) {
            return;
        }
        _menuNavigationService.NavigateTo(SelectedMenuItem.View);
    }
}


public class MenuItem {
    public string View { get; private init; }
    public string Name { get; private init; }

    private MenuItem() {
    }

    private static MenuItem BudgetView =>
        new() { Name = "查看预算", View = MenuNavigationConstant.BudgetView };

    private static MenuItem CategoryView =>
        new() { Name = "类别管理", View = MenuNavigationConstant.CategoryView };

    private static MenuItem IncomeExpensesView =>
        new() { Name = "收支记录", View = MenuNavigationConstant.IncomeExpensesView };
    
    private static MenuItem GlobalSearchView =>
        new() { Name = "全局搜索", View = MenuNavigationConstant.GlobalSearchView };
    
    private static MenuItem VisualizationView =>
        new() { Name = "账单图表", View = MenuNavigationConstant.VisualizationView };
    
    // 有分类管理
    // public static IEnumerable<MenuItem> MenuItems { get; } = [
    //     BudgetView, CategoryView, IncomeExpensesView
    // ];
    //
    
    // 无分类管理，有全局搜索
    public static IEnumerable<MenuItem> MenuItems { get; } = [
        BudgetView, IncomeExpensesView, GlobalSearchView, VisualizationView, CategoryView
    ];
    
}